package com.xiaoliang.servlet;

import com.xiaoliang.entry.Page;
import com.xiaoliang.entry.Product;
import com.xiaoliang.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author XIAOLIANG
 * @ClassName FuzzyQuery.java
 * @Description TODO
 * @createTime 2021年02月28日 17:31:00
 */
//@WebServlet("/product/queryList")
public class FuzzyQuery extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		ProductServiceImpl productService = new ProductServiceImpl();


//获取参数
		String productName = req.getParameter("productName");
		String operation = req.getParameter("operation");
		String price = req.getParameter("price");

		Integer pageNum = req.getParameter("pageNum")!=null?Integer.parseInt(req.getParameter("pageNum")):1;
		Integer pageSize = req.getParameter("pageSize")!=null?Integer.parseInt(req.getParameter("pageSize")):3;


		//获取查询总条数  并初始化分页信息
		Integer count = productService.getCountByCondition(productName,operation,price); //
		Page page = new Page(pageSize, pageNum);
		page.setTotleElements(count);
//		List<Product> products = productService.selectPage(pageNum,pageSize);

		//获取 当前页数据
		List<Product> products = productService.searchByCondition(productName, operation, price, pageNum, pageSize);

		//list页面需要用到的数据
		req.setAttribute("page",page);
		req.setAttribute("products",products);
		req.setAttribute("productName",productName);
		req.setAttribute("operation",operation);
		req.setAttribute("price",price);

		Map<String, String[]> params = req.getParameterMap();    //获取最近一次 productlist.jsp页面 完整的请求地址 并将其存进session
		String queryString = "";
		for (String key : params.keySet()) {
			String[] values = params.get(key);
			for (int i = 0; i < values.length; i++) {
				String value = values[i];
				queryString += key + "=" + value + "&";
			}
		}
		// 去掉最后一个空格
//		queryString = queryString.substring(0, queryString.length()-1);
		if (queryString.endsWith("?")||queryString.endsWith("&")){
			queryString = queryString.substring(0,queryString.length()-1);
		}
		System.out.println("进入querylist 完整的请求地址是:"+req.getRequestURL()+"?"+queryString);

		req.getSession().setAttribute("queryString",queryString);

		req.getRequestDispatcher("/product/searchList.jsp").forward(req,resp);

	}
}
